package cn.darven.db;

import cn.darven.config.ConfigLoader;

import java.sql.*;

/**
 * @author darven
 * @date 2025/11/3
 * @description SQL Server 数据库操作
 */
public class SQLServerDB {

    private Connection connection;

    // 连接
    public SQLServerDB() {
        String url = ConfigLoader.get("db.url");
        String username = ConfigLoader.get("db.username");
        String password = ConfigLoader.get("db.password");
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 查询数据
    public String fetchXmlData() {
        String sql = "SELECT " +
                "id AS '@id', " +
                "name AS 'name', " +
                "gender AS 'gender', " +
                "email AS 'contact/email', " +
                "phone AS 'contact/phone', " +
                "tags AS 'tags' " +
                "FROM Contacts " +
                "FOR XML PATH('contact'), ROOT('contacts')";

        try {
            // 创建Statement对象
            Statement statement = connection.createStatement();
            // 执行数据库语句
            ResultSet resultSet = statement.executeQuery(sql);

            if (resultSet.next()) {
                return resultSet.getString(1);
            }
            return "";
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
